package com.goldpac.cardbiz.utils;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.URLDecoder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.misc.BASE64Decoder;

/**
 * 功能描述： File工具类
 * 
 * @author Administrator
 * @Date Jul 19, 2008
 * @Time 9:46:11 AM
 * @version 1.0
 */
public class FileUtil {
    public static final String FILE_SEPARATOR = System.getProperty("file.separator");
    private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 功能描述：拷贝一个目录或者文件到指定路径下，即把源文件拷贝到目标文件路径下
     * 
     * @param source 源文件
     * @param target 目标文件路径
     * @return void
     */
    public static void copy(File source, File target) {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(source); // 用于读取文件的原始字节流
            os = new FileOutputStream(target); // 用于写入文件的原始字节的流
            byte[] buf = new byte[1024];// 存储读取数据的缓冲区大小
            int len = 0;
            while ((len = is.read(buf)) != -1) {
                os.write(buf, 0, len);
            }
            is.close();
            os.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }
        // }
    }

    /**
     * 使用文件通道的方式复制文件
     * 
     * @param s 源文件
     * @param t 复制到的新文件
     */
    public static void fileChannelCopy(File s, File t) {
        FileInputStream fi = null;
        FileOutputStream fo = null;
        FileChannel in = null;
        FileChannel out = null;
        try {
            if (!t.exists()) {
                t.mkdir();
                t.createNewFile();
            }
            fi = new FileInputStream(s);
            fo = new FileOutputStream(t);
            in = fi.getChannel();// 得到对应的文件通道
            out = fo.getChannel();// 得到对应的文件通道
            in.transferTo(0, in.size(), out);// 连接两个通道，并且从in通道读取，然后写入out通道
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fi != null) {
                    fi.close();
                }
                if (in != null) {
                    in.close();
                }
                if (fo != null) {
                    fo.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 使用文件通道的方式复制文件
     * 
     * @Title: fileChannelCopy
     * @param oldFilePath 旧文件绝对路径
     * @param newFilePath 新文件绝对路径
     */
    public static synchronized void fileChannelCopy(String oldFilePath, String newFilePath) {
        FileInputStream fi = null;
        FileOutputStream fo = null;
        FileChannel in = null;
        FileChannel out = null;
        try {
            fi = new FileInputStream(new File(oldFilePath));
            fo = new FileOutputStream(new File(newFilePath));
            in = fi.getChannel();// 得到对应的文件通道
            out = fo.getChannel();// 得到对应的文件通道
            in.transferTo(0, in.size(), out);// 连接两个通道，并且从in通道读取，然后写入out通道
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fi != null) {
                    fi.close();
                }
                if (in != null) {
                    in.close();
                }
                if (fo != null) {
                    fo.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 删除指定目录及其中的所有内容。
     * 
     * @param dir 要删除的目录
     * @return 删除成功时返回true，否则返回false。
     * @since 1.0
     */
    public static boolean deleteDirectory(File dir) {
        if ((dir == null) || !dir.isDirectory()) {
            // throw new IllegalArgumentException("Argument " + dir +
            // " is not a directory. ");
            return false;
        }
        File[] entries = dir.listFiles();
        int sz = entries.length;
        for (int i = 0; i < sz; i++) {
            if (entries[i].isDirectory()) {
                if (!deleteDirectory(entries[i])) {
                    return false;
                }
            } else {
                if (!entries[i].delete()) {
                    return false;
                }
            }
        }
        if (!dir.delete()) {
            return false;
        }
        return true;
    }

    /**
     * 删除指定的文件
     * 
     * @param filePath
     */
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (file != null) {
            if (file.exists()) {
                file.delete();
                return true;
            }
        }
        return false;
    }

    // base64字符串转化成图片
    public static boolean GenerateImage(String imgStr, String filePath) { // 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            String strDecode = URLDecoder.decode(imgStr, "UTF-8");
            // Base64解码
            byte[] b = decoder.decodeBuffer(strDecode);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            // 生成jpeg图片
            // String imgFilePath = "d://222.png";// 新生成的图片
            out = new FileOutputStream(filePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将指定的文件夹copy到指定的路径下，如果指定的制定的路径不存在，创建此路径;指定的路径存在将覆盖.
     * 
     * @param directoryPath 全路径
     * @param toDirectoryPath 全路径
     * @return 是否成功 成功==true.
     */
    public static boolean copyDirectory(String directoryPath, String toDirectoryPath) {
        File file;
        File[] files;
        file = new File(directoryPath);
        if (file.exists() && file.isDirectory()) {
            files = file.listFiles();
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    if (files[i].exists()) {
                        if (files[i].isDirectory()) {
                            copyDirectory(files[i].getPath(), toDirectoryPath + FILE_SEPARATOR + files[i].getName());
                        } else if (files[i].isFile()) {
                            copyFile(files[i].getPath(), toDirectoryPath);
                        }
                    }
                }
            }
        } else {
            return false;
        }
        return true;
    }

    /**
     * 将指定的文件copy到指定的路径下，如果该路径不存在将创建此路径。
     * 
     * @param filePath 全路径
     * @param toDirectoryPath 全路径
     * @return 是否成功 成功==true.
     */
    public static boolean copyFile(String filePath, String toDirectoryPath) {
        if (filePath == null || toDirectoryPath == null) {
            return false;
        } else if (filePath.trim().equals("") || toDirectoryPath.trim().equals("")) {
            return false;
        }
        File directory = new File(toDirectoryPath);
        if (!directory.exists()) {
            makeDirectory(toDirectoryPath);
        }
        File file = new File(filePath);
        String toFilePath = toDirectoryPath + FILE_SEPARATOR + file.getName();
        File toFile = new File(toFilePath);
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            if (!file.isFile()) {
                return false;
            }
            fis = new FileInputStream(file);
            fos = new FileOutputStream(toFile);
            byte[] data = new byte[fis.available()];
            int bytesRead;
            while ((bytesRead = fis.read(data)) != -1) {
                fos.write(data, 0, bytesRead);
            }
            fos.flush();
            fos.close();
            fis.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 从给定的字符串中创建文件系统路径。
     * 
     * @param directory 给定的路径表示字符串。
     * @return 是否成功 成功==true.
     */
    public static boolean makeDirectory(String directory) {
        File file = new File(directory);
        if (!file.exists()) {
            if (file.mkdirs()) {
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }

    public static boolean writeToFile(String filePath, String content) {
        logger.error("writeToFile : " + filePath);
        BufferedWriter bwIc = null;
        try {
            File inputData = new File(filePath);
            inputData.setWritable(true, false);
            if (inputData.exists()) {
                inputData.delete();
            }
            if (!inputData.exists()) {
                inputData.createNewFile();
            }
            bwIc = new BufferedWriter(new FileWriter(inputData));
            bwIc.write(content);
            bwIc.flush();

            logger.error("writeToFile--------------------------------------->OK");
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            if (bwIc != null) {
                try {
                    bwIc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    public static int getTotalLines(String fileName) throws IOException {
        BufferedReader in = null;
        LineNumberReader reader = null;
        int lines = 0;
        try {
            in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
            reader = new LineNumberReader(in);
            String s = reader.readLine();
            while (s != null) {
                lines++;
                s = reader.readLine();
            }
            reader.close();
            in.close();
            return lines;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null)
                in.close();
            if (reader != null)
                reader.close();
        }
        return lines;

    }

    public static String readLineVarFile(String fileName, int lineNumber) throws IOException {
        BufferedReader reader = null;
        StringBuffer sb = new StringBuffer();
        try {
            Path path = Paths.get(fileName);
            File file = path.toFile();
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            String line = reader.readLine();
            int total = getTotalLines(fileName);
            if (lineNumber < 0 || lineNumber > total) {
                System.out.println("不在文件的行数范围之内。");
            }
            int stratNum = total - lineNumber;
            int num = 0;
            while (line != null) {
                num++;
                if (num > stratNum) {
                    // System.out.println("line " + lineNumber + ": " + line);
                    sb.append(line);
                    sb.append("\n");
                }
                line = reader.readLine();
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null)
                reader.close();
        }
        return sb.toString();
    }

    /**
     * 读取文件内容
     * 
     * @Title: getContent
     * @param filePath
     * @return
     * @throws IOException
     */
    @SuppressWarnings("resource")
    public byte[] getContent(String filePath) throws IOException {
        File f = new File(filePath);
        if (!f.exists()) {
            logger.error("file is not exist...");
            return null;
        }
        FileChannel fc = null;
        try {
            fc = new RandomAccessFile(filePath, "r").getChannel();
            MappedByteBuffer byteBuffer = fc.map(MapMode.READ_ONLY, 0, fc.size()).load();
            if (fc.size() > Integer.MAX_VALUE) {
                // System.out.println("file too big...");
                logger.error("file too big...");
                return null;
            }
            byte[] result = new byte[(int)fc.size()];
            if (byteBuffer.remaining() > 0) {
                byteBuffer.get(result, 0, byteBuffer.remaining());
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            throw e;
        } finally {
            try {
                if (fc != null) {
                    fc.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据byte数组，生成文件
     */
    public static void witerByteToFile(byte[] bfile, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            dir.setWritable(true, false);
            if (!dir.exists() && dir.isDirectory()) {// 判断文件目录是否存在
                dir.mkdirs();
            }
            file = new File(filePath + FILE_SEPARATOR + fileName);
            file.setWritable(true, false);
            if (!file.exists()) {
                file.createNewFile();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bfile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

}
